package service

import (
	"api_interface/dao"
	"api_interface/entity"

	"github.com/jinzhu/gorm"
)

// 发起提问（测试完成）
func CreateQues(question *entity.QuestionInfo) (err error) {
	if err = dao.SqlSession.Create(question).Error; err != nil {
		return err
	}
	return
}

// 查看提问箱中的所有提问（测试完成）
func GetQuesFromBox(aid int, bid int) (questionWithLiked *[]entity.QuestionInfoWithLiked, err error) {
	var queslist []entity.QuestionInfo
	if err = dao.SqlSession.Where("bid=?", bid).Find(&queslist).Error; err != nil {
		return nil, err
	}
	var quesWithLikedlist []entity.QuestionInfoWithLiked
	for i, data := range queslist {
		var l bool
		var likes []entity.LikedInfo
		dao.SqlSession.Where("aid = ? AND qid = ?", aid, data.Id).Find(&likes)
		if len(likes) == 0 {
			l = false
		} else {
			l = true
		}
		quesWithLikedlist = append(quesWithLikedlist, entity.QuestionInfoWithLiked{
			Ques:  queslist[i],
			Liked: l,
		})
	}
	questionWithLiked = &quesWithLikedlist
	return
}

// 查询提问详细内容（测试完成）
func GetQuesById(id int) (question *entity.QuestionInfo, err1 error, err2 error) {
	var ques_info entity.QuestionInfo

	if err1 = dao.SqlSession.Where("id=?", id).First(&ques_info).Error; err1 != nil {
		return nil, err1, nil
	}
	if err2 = dao.SqlSession.Model(&entity.QuestionInfo{}).Where("id=?", id).Update("views", gorm.Expr("views + 1")).Error; err2 != nil {
		return nil, nil, err2
	}
	ques_info.Views++
	question = &ques_info
	return
}

// 搜索提问箱中的某一提问（测试完成）
func SearchQuesFromBox(bid int, title string) (question *[]entity.QuestionInfo, err error) {
	var quesList []entity.QuestionInfo
	if err = dao.SqlSession.Where("bid=? AND title LIKE ?", bid, "%"+title+"%").Find(&quesList).Error; err != nil {
		return nil, err
	}
	question = &quesList
	return
}

//删除提问（测试完成）

func DeleteQues(id string) (err error) {
	err = dao.SqlSession.Where("id=?", id).Delete(&entity.QuestionInfo{}).Error
	return
}

//点赞提问or取消点赞（测试完成）

func LikeQuesOrDeleteLike(aid int, qid int) (err error) {
	var likedInfo entity.LikedInfo
	tx := dao.SqlSession.Begin()
	// 先查找是否存在点赞记录
	if err := tx.Where("aid =? AND qid =?", aid, qid).First(&likedInfo).Error; err == nil {
		// 记录存在，执行取消点赞操作（QuestionInfo的Lik减一，并删除LikedInfo记录）
		if err := tx.Model(&entity.QuestionInfo{}).Where("id =?", qid).Update("lik", gorm.Expr("lik -?", 1)).Error; err != nil {
			tx.Rollback()
			return err
		}
		if err := tx.Where("aid =? AND qid =?", aid, qid).Delete(&entity.LikedInfo{}).Error; err != nil {
			tx.Rollback()
			return err
		}
	} else if gorm.ErrRecordNotFound == err {
		// 记录不存在，执行点赞操作（QuestionInfo的Lik加一，并创建新的LikedInfo记录）
		if err := tx.Model(&entity.QuestionInfo{}).Where("id =?", qid).Update("lik", gorm.Expr("lik +?", 1)).Error; err != nil {
			tx.Rollback()
			return err
		}
		newLikedInfo := entity.LikedInfo{
			Cid: 2,
			Aid: aid,
			Qid: qid,
		}
		if err := tx.Create(&newLikedInfo).Error; err != nil {
			tx.Rollback()
			return err
		}
	} else {
		tx.Rollback()
		return err
	}
	return tx.Commit().Error
}
